package com.itheima.exception;

import com.itheima.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){

        //1.获取异常信息
        String message=e.getMessage();

        if (message.contains("Duplicate entry")) {
            //2.切割内容
            String result= message.split(" ")[2]+",已存在! ";

            return R.error(result);
        }
        return R.error("未知错误");
    }


    //删除菜品分类自定义异常
    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e){
        e.printStackTrace();
        return R.error(e.getMessage());
    }

}